using System;
using System.Collections;
using System.Collections.Generic;
using SciptableObject;
using UnityEngine;
using Utilities;
using EventHandler = Utilities.EventHandler;

public class DataCenterManager : MonoBehaviour
{
    private  GameValues value;
    private GameValues oldValue;
    private float maxFaith;
    public float waitSec;
    private void Start()
    {
        InitGameValue();
        StartCoroutine(FaithPower());
    }
    

    private void OnEnable()
    {
        EventHandler.GameDataValueSend += ComputeValue;
    }

    private void OnDisable()
    {
        EventHandler.GameDataValueSend -= ComputeValue;
    }
    /// <summary>
    /// 设置初始值
    /// </summary>
    private void InitGameValue()
    {
        value = new GameValues
            { 
                faith = 50, 
                happiness = 50, 
                height = 0, 
                numberOfPeople = 1, 
                score = 0, 
                technology = 25 
            };
        maxFaith = value.faith;
        EventHandler.CallValueToUI(value);
    }
    /// <summary>
    /// 计算当前数值并呼叫广播传递给UI
    /// </summary>
    /// <param name="list"></param>
    /// <param name="flag"></param>
    private void ComputeValue(List<EventRewordData> list, bool flag)
    {
        oldValue = value;
        int multiplier = flag ? 1 : -1;

        foreach (var data in list)
        {
            switch (data.type)
            {
                case TargetValueType.Faith:
                    value.faith += multiplier * data.value;
                    break;
                case TargetValueType.Happiness:
                    value.happiness += multiplier * data.value;
                    break;
                case TargetValueType.Technology:
                    value.technology += multiplier * data.value;
                    break;
                case TargetValueType.NumberOfPeople:
                    value.numberOfPeople += multiplier * data.value;
                    break;
            }
        }
        maxFaith = value.faith;
        EventHandler.CallValueToUI(value);
        ChangePeopleNum();
    }

    private void ChangePeopleNum()
    {
        var amount = oldValue.numberOfPeople - value.numberOfPeople;
        var action = amount < 0 
            ? (System.Action)(() => MiniPeopleManager.Instance.CreateMiniPeople()) 
            : () => MiniPeopleManager.Instance.RemoveMiniPeople();
        for (int i = 0; i < Mathf.Abs(amount); i++)
        {
            action();
        }
    }

    IEnumerator FaithPower()
    {
        while (true)
        {
            yield return new WaitForSeconds(1f);
            EventHandler.CallFaithValueToUI(maxFaith/waitSec);
            // Debug.Log(maxFaith/waitSec);
        }
    }
    
}
public struct GameValues
{
    public float height;//高度
    public float score; //位移（分数）
    public float faith; // 信仰值
    public float technology; // 科技值
    public float happiness;  // 幸福值
    public float numberOfPeople; // 人数
}